<?php

class SysappaccessruleController extends Controller
{
        private $arrExceptedActionFunction = array('actions', 'actionError', 'actionContact', 'actionLogin', 'actionLogout', 'actionChecklist', 'actionArmanage');
        private $arrExceptedController = array('Default','Sysappaccessrule','SpecialAjax','Site', 'AppReport');
        
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	*/ 
            public function accessRules()
            {
                    return array(
                            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                                    'actions'=>array('index','view','create','update', 'armanage', 'armanage2', 'admin','delete'),
                                    'users'=>array('ganda'),
                            ),
                            array('deny',  // deny all users
                                    'users'=>array('*'),
                            ),
                    );
            }
        //*/
        
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID),
		));
	}

        private function getActionRuleData($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID, $RuleValues, $isArrayRuleValues){
            $accRuleData = Sysappaccessrule::model()->find("MenuGroupID={$MenuGroupID} and PermissionAccessID= {$PermissionAccessID} and ControllerName = '{$ControllerName}' and RuleTypeID={$RuleTypeID}");
            $modelValue = new Sysappaccessrule;
            if (isset($accRuleData)){
                $modelValue = $accRuleData;
                $modelValue->isNewRecord = false;
                $modelValue->RuleGroupArray = $RuleGroupArray;
                $modelValue->RuleTypeID = $RuleTypeID;
                $modelValue->RuleValues = $RuleValues;
                $modelValue->isActive = 1;
                $modelValue->LastUpdateBy = Yii::app()->user->name;
                $modelValue->LastUpdateOn = Date("Y-m-d g:i:s");
            }else{
                $modelValue = new Sysappaccessrule;
                $modelValue->isNewRecord = true;
                $modelValue->MenuGroupID = $MenuGroupID;
                $modelValue->RuleGroupArray = $RuleGroupArray;
                $modelValue->PermissionAccessID = $PermissionAccessID;
                $modelValue->ControllerName = $ControllerName;
                $modelValue->RuleTypeID = $RuleTypeID;
                $modelValue->RuleValues = $RuleValues;
                $modelValue->isArrayRuleValues = $isArrayRuleValues;
                $modelValue->isActive = 1;
                $modelValue->CreatedBy = Yii::app()->user->name;
                $modelValue->CreatedOn = Date("Y-m-d g:i:s");
            }
            
            return $modelValue;
        }
 
        private function getAllControllerAndFunction($startpath){
            $ite=new RecursiveDirectoryIterator($startpath);

            $controllerList = array();
            foreach (new RecursiveIteratorIterator($ite) as $filePath) {
                $arrPathSplit = explode("\\", $filePath);

                $fileName = $arrPathSplit[count($arrPathSplit) - 1];
                if(is_file($filePath)){
                    if (strpos($fileName,'Controller.php') !== false) {
                        $fileContains = file_get_contents($filePath);
                        $strClass = $fileContains;
                        $strFunc = $fileContains;

                        if(strpos($strClass, 'class') !==FALSE){
                            $expStrClass = explode('class',$strClass);
                            $strClass = $expStrClass[1];
                            if(strpos($strClass, '{') !==FALSE){
                                $expStrClass = explode('{',$strClass);
                                $strClass = $expStrClass[0];

                                if(strpos($strClass, 'extends') !==FALSE){
                                    $expStrClass = explode('extends',$strClass);
                                    $strClass = trim($expStrClass[0]);
                                    $controllerList[$strClass] = array();

                                    $arrFunction = array();
                                    $expStrFunc = explode('function',$strFunc);
                                    for($i = 1; $i < count($expStrFunc); $i++){
                                        $expfuncs = explode('(', $expStrFunc[$i]);
                                        $funcName = trim($expfuncs[0]);
                                        if(strpos($funcName, 'action') !==FALSE){
                                            array_push($arrFunction, $funcName);
                                        }
                                    }
                                    $controllerList[$strClass] = $arrFunction;
                                }
                            }
                        }
                    }
                }
            }
            
            return $controllerList;
        }
        
        public function actionArmanage()
        {
            $model = new Sysappaccessrule;
            $menuGroupModel = new Sysappmenugroup;
            $allActionChecked = array();
            $modelList = array();
            
            $appControllerPath = Yii::getPathOfAlias('application.modules.*'); 
            
            $controllerList = $this->getAllControllerAndFunction($appControllerPath);
            $arrAllAction = array();
            foreach ($controllerList as $funct){
                foreach ($funct as $f){
                    if(is_int(strpos($f, 'action')) && !is_int(array_search($f, $this->arrExceptedActionFunction))){
                        $arrAllAction[$f] = $f;
                    }
                }
            }
            
            if(isset($_POST['ajax']) && $_POST['ajax']==='client-account-create-form')
            {
                foreach ($modelList as $mod) {
                    echo CActiveForm::validate($mod);
                }
                Yii::app()->end();
            }

            if(isset($_POST['Sysappaccessrule']))
            {
                $model->attributes=$_POST['Sysappaccessrule'];
                $menuGroup = $model->MenuGroupID;
             
                $deleteData = new Sysappaccessrule;
                $deleteData->isNewRecord=false;
                $deleteData->deleteAll("MenuGroupID={$menuGroup} and RuleGroupArray in (1,2) and RuleTypeID in (1,2)");

                foreach (array_keys($controllerList) as $controllerClassName) {
                    $controllerName = str_replace("Controller", "", $controllerClassName);
                    
                    if(strpos($controllerClassName, 'Controller') ===FALSE)
                        continue;
                    
                    if (is_int(array_search($controllerName, $this->arrExceptedController)))
                        continue;
                    
                    $arrRuleValues = array();
                    
                    foreach ($arrAllAction as $f){
                        $fr = str_replace("action", '', $f);
                        if(isset($_POST[$controllerName.'_'.strtolower($fr)]))array_push($arrRuleValues, "'".strtolower($fr)."'");
                    }
                    $ruleValues = (!empty($arrRuleValues))?implode(',', $arrRuleValues):"";
                    
                    if($ruleValues===""){
                        continue;
                    }
                    $allActionChecked[$controllerName] = $arrRuleValues;
                    
                    $modelList[$controllerName] = $this->getActionRuleData($menuGroup, 1, 1, $controllerName, 1, $ruleValues, 1);
                    
                    if($modelList[$controllerName]->validate())
                    {
                        if($this->saveModel($modelList[$controllerName])==""){
                            //set Allow User Default
                            $model2 = $this->getActionRuleData($menuGroup, 1, 1, $controllerName, 2, '@', 1);
                            if($this->saveModel($model2)!="")
                                throw new CHttpException(404,'Save Access Rule Step 2 Failed.');
                            
                            //set Deny User Default
                            $model3 = $this->getActionRuleData($menuGroup, 2, 2, $controllerName, 2, '*', 1);
                            
                            if($this->saveModel($model3)!="")
                                throw new CHttpException(404,'Save Access Rule Step 3 Failed.');
            
                            Yii::app()->user->setFlash('message', '<font color="blue">Saving data Successfully</font>');
                        }else{
                            throw new CHttpException(404,'Save Access Rule Step 1 Failed.');
                        }
                    }
                }
            }
                if(isset($model->MenuGroupID)){
                $menuGroupModel = Sysappmenugroup::model()->find("MenuGroupID='{$model->MenuGroupID}'");
            }
            
            $this->render('armanage',array('model'=>$model, 'menuGroupModel'=>$menuGroupModel, 'arrExceptedActionFunction'=>$this->arrExceptedActionFunction, 'arrExceptedController'=>  $this->arrExceptedController, 'allActionChecked'=>$allActionChecked, 'arrAllAction'=>$arrAllAction, 'controllerList'=>$controllerList));
        }

        //*/
        
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
                $model=new Sysappaccessrule;
                
                $model->CreatedBy = Yii::app()->user->name;
                $model->CreatedOn = Date("Y-m-d g:i:s");

                
                if(isset($_POST['ajax']) && $_POST['ajax']==='client-account-create-form')
                {
                    echo CActiveForm::validate($model);
                    Yii::app()->end();
                }

                if(isset($_POST['Sysappaccessrule']))
                {
                    $model->attributes=$_POST['Sysappaccessrule'];
                    if($model->validate())
                    {
                            $session = Yii::app()->session;
                            if(!empty ($session['SessionText'])){
                                $SessionText = $session['SessionText'];
                            }

                            $this->saveModel($model);
                            $this->redirect(array('view','MenuGroupID'=>$model->MenuGroupID, 'RuleGroupArray'=>$model->RuleGroupArray, 'PermissionAccessID'=>$model->PermissionAccessID, 'ControllerName'=>$model->ControllerName, 'RuleTypeID'=>$model->RuleTypeID));
                    }
                }
                $this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID)
	{
                $model=$this->loadModel($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID);
                
                $model->LastUpdateBy = Yii::app()->user->name;
                $model->LastUpdateOn = Date("Y-m-d g:i:s");

                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Sysappaccessrule']))
		{
			$model->attributes=$_POST['Sysappaccessrule'];
			$this->saveModel($model);
			$this->redirect(array('view',
	                    'MenuGroupID'=>$model->MenuGroupID, 'RuleGroupArray'=>$model->RuleGroupArray, 'PermissionAccessID'=>$model->PermissionAccessID, 'ControllerName'=>$model->ControllerName, 'RuleTypeID'=>$model->RuleTypeID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID)
	{
                if(Yii::app()->request->isPostRequest)
		{
			try
			{
				// we only allow deletion via POST request
				$this->loadModel($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID)->delete();
			}
			catch(Exception $e) 
			{
				$this->showError($e);
			}

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Sysappaccessrule');
                
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
                $model=new Sysappaccessrule('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Sysappaccessrule']))
			$model->attributes=$_GET['Sysappaccessrule'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Sysappaccessrule the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($MenuGroupID, $RuleGroupArray, $PermissionAccessID, $ControllerName, $RuleTypeID)
	{
                $model=Sysappaccessrule::model()->findByPk(array('MenuGroupID'=>$MenuGroupID, 'RuleGroupArray'=>$RuleGroupArray, 'PermissionAccessID'=>$PermissionAccessID, 'ControllerName'=>$ControllerName, 'RuleTypeID'=>$RuleTypeID));
		if($model==null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Sysappaccessrule $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sysappaccessrule-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function saveModel($model)
	{
		try
		{
			$model->save();
		}
		catch(Exception $e)
		{
			$this->showError($e);
		}		
	}
        
        function showError(Exception $e)
	{
		if($e->getCode()==23000)
			$message = "This operation is not permitted due to an existing foreign key reference.";
		else
			$message = "Invalid operation.";
		throw new CHttpException($e->getCode(), $message);
	}
}
